#include "cJSON.h"
#include "log.h"
#include "stdlib.h"

int main(int argc, char const *argv[])
{
    // 1.测试将字符串转换成JSON串
    cJSON *cjson = cJSON_CreateObject();

    cJSON_AddStringToObject(cjson, "name", "xiaowang");
    cJSON_AddNumberToObject(cjson, "age", 18);
    cJSON_AddStringToObject(cjson, "city", "shanghai");

    char *cjson_str = cJSON_PrintUnformatted(cjson);
    log_info("生成的JSON串为:%s", cjson_str);

    // 2.测试从JSON串中解析出字符串
    char *json_str = {"{\"name\":\"zhangsan\",\"age\":22,\"city\":\"beijing\"}"};
    // log_info("json_str = %s",json_str);

    cJSON *root = cJSON_Parse(json_str);
    // cJSON *root = cJSON_Parse(cjson_str);
    if (root == NULL)
    {
        log_debug("JSON 解析失败...");
        return -1;
    }

    cJSON *name_cjson = cJSON_GetObjectItem(root, "name");
    cJSON *age_cjson = cJSON_GetObjectItem(root, "age");
    cJSON *city_cjson = cJSON_GetObjectItem(root, "city");
    if (name_cjson == NULL || age_cjson == NULL || city_cjson == NULL)
    {
        log_debug("name或age或city解析失败...");
        return -1;
    }

    char *name = name_cjson->valuestring;
    int age = age_cjson->valueint;
    char *city = city_cjson->valuestring;

    log_info("解析出来的字符串为:name:%s, age:%d, city:%s", name, age, city);

    cJSON_Delete(root);
    cJSON_Delete(cjson);

    free(cjson_str);

    return 0;
}
